$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'dataworks/flow/list',
        datatype: "json",
        mtype: "POST",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, search: false,key: true },
			{ label: '作业名称', name: 'name', index: 'name', width: 80 },
			{ label: '调度任务', name: 'jobinfoId', index: 'jobinfo_id', search: false,width: 80 },
            { label: '操作', name: 'id', width: 80, search: false, formatter: function(value, options, row){
                    var f = '<a class="btn btn-primary btn-sm " href="#"  onclick="vm.workDev(\'' + value + '\')">作业<i class="fa fa-coffee"></i></a> ';
                    return f;
            }}
        ],
		viewrecords: true,
        height: 'auto',
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        //width: document.body.clientWidth,根据body的宽度使用这个请注释掉autowidth:true
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "data.data",
            page: "data.pageNum",
            total: "data.pages",
            records: "data.recordCounts"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        postData:{'spaceId': getCookie("user_space_id")},
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    $("#jqGrid").filterToolbar({}).jqGrid('navGrid',"#jqGridPager",{//刷新按钮
        refresh: true,
        edit:false,del: false,search:false,add:false
    });
    vm.loadSpace();
});

var vm = new Vue({
	el:'#rrapp',
	data:{
        triggerStatusEnable: true,
		showList: true,
        showInfo: false,
        showFlow: false,
        showJobInfoAdd: false,
		title: null,
        spaceList: [],
		flow: {},
        jobinfo: {
            triggerStatus: 0,
            addressList: null,
            addressType: 0,
            executorHandler: 'executorJobHandler',
            scheduleConf: '0 0 1 * * ?'
        }
	},
	methods: {
		query: function () {
			vm.reload();
		},
        loadSpace: function(){
            $.ajax({
                type: "POST",
                url: baseURL + "workspace/space/list",
                contentType: "application/json",
                header: {limit: 100000},
                data: {},
                success: function(r){
                    if(r.code === 0){
                        vm.spaceList = r.data.data;
                    }else{
                        layer.alert(r.msg);
                    }
                }
            });
        },
		add: function(){
			vm.showList = false;
			vm.showFlow = false;
			vm.showInfo = true;
			vm.title = "新增";
			vm.flow = {spaceId:getCookie("user_space_id")};
		},
        devWorkCancel: function(){
            vm.showList = true;
            vm.showFlow = false;
            vm.showInfo = false;
            vm.reload();
        },
        workDev: function(id){
            var child = document.getElementById("flowWorkIFrame").contentWindow;

            vm.getInfo(id, function(data){
                child.initFlow(data);
            });

            vm.showList = false;
            vm.showFlow = true;
            vm.showInfo = false;

            var domHeight = document.documentElement.clientHeight-50;
            $("#flowWorkDiv").height(domHeight + 29);
        },
        saveFlowScript: function(){
            var child = document.getElementById("flowWorkIFrame").contentWindow;
            child.buildFlowScript(true);
        },
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
            vm.showList = false;
            vm.showFlow = false;
            vm.showInfo = true;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                var url = vm.flow.id == null ? "dataworks/flow/save" : "dataworks/flow/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.flow),
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "dataworks/flow/deleteBatch",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
		getInfo: function(id, callback){
			$.get(baseURL + "dataworks/flow/info/"+id, function(r){
                if(r.code == 0){
                    vm.flow = r.data;
                    if(callback){
                        callback(r.data);
                    }
                }else{
                    alert(r.msg);
                }
            });
		},
		reload: function (event) {
            vm.showList = true;
            vm.showFlow = false;
            vm.showInfo = false;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
        executeJob: function(){
            if(vm.flow.jobinfoId == null || vm.flow.jobinfoId == ""){
                alert("请先完成【调度配置】初始化!!!");
                return;
            }
            var child = document.getElementById("flowWorkIFrame").contentWindow;
            vm.flow.flowScript = child.buildFlowScript(false);
            if(vm.flow.flowScript == null){
                return;
            }
            $.ajax({
                type: "POST",
                url: baseURL + "dataworks/flow/executeJob",
                contentType: "application/json",
                data: JSON.stringify(vm.flow),
                success: function (r) {
                    if (r.code == 0) {
                        if(r.data != null){
                            vm.showDetail(r.data, true);
                        }else{
                            layer.msg("操作成功", {icon: 1});
                        }
                    } else {
                        layer.alert(r.msg);
                    }
                }
            });
        },
        killJob: function(logId, callBack){
            layer.confirm( ('确定终止任务?'), {
                icon: 3,
                title: '系统提示' ,
                btn: [ '确定', '取消' ]
            }, function(index){
                layer.close(index);
                $.ajax({
                    type : 'POST',
                    url : baseURL + 'joblog/logKill',
                    data : {"id":logId},
                    dataType : "json",
                    success : function(r){
                        if (r.code == 200) {
                            layer.alert('操作成功');
                            if(callBack){
                                callBack();
                            }
                        } else {
                            layer.alert(r.msg);
                        }
                    },
                });
            });
        },
        convertSelectVal: function(obj){
            if(!obj){
                // obj不存在则获取值绑定到vm对象
                vm.jobinfo.jobGroup = $("#jobGroup").val();
                vm.jobinfo.executorRouteStrategy = $("#executorRouteStrategy").val();
                vm.jobinfo.glueType = $("#glueType").val();
                vm.jobinfo.executorBlockStrategy = $("#executorBlockStrategy").val();
                vm.jobinfo.misfireStrategy = $("#misfireStrategy").val();
                vm.jobinfo.scheduleType = $("#scheduleType").val();
            }else{
                // obj存在则获取obj值绑定到dom对象
                $("#jobGroup").val(vm.jobinfo.jobGroup).attr("disabled","disabled");
                $("#executorRouteStrategy").val(vm.jobinfo.executorRouteStrategy);
                $("#glueType").val(vm.jobinfo.glueType);
                $("#executorBlockStrategy").val(vm.jobinfo.executorBlockStrategy);
                $("#misfireStrategy").val(vm.jobinfo.misfireStrategy);
                $("#scheduleType").val(vm.jobinfo.scheduleType).attr("disabled","disabled");
            }
        },
        showDetail: function(logId, isRun){
            var index = layer.open({
                type: 2,
                scrollbar: false,
                title: false,
                area: ['100%', '100%'],
                shadeClose: false,
                closeBtn: false,
                shade:0.7,
                skin: 'myskin',
                content: baseURL + 'joblog/logDetailPage?id=' + logId,
                success: function(layero, index){
                    var child = document.getElementById("layui-layer-iframe"+index).contentWindow;
                    // 初始化传递layer下标，用于iframe控制父窗口组件
                    child.initLayer(index);
                },
                btn: ['暂停刷新', '终止任务', '关闭']
                ,yes: function(index, layero){
                    var child = document.getElementById("layui-layer-iframe"+index).contentWindow;
                    var btn = $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn0");
                    if(btn.html() == "暂停刷新"){
                        child.logRunStop("暂停刷新...");
                        $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn0").html("继续刷新");
                    }else{
                        child.logRunFn();
                        $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn0").html("暂停刷新");
                    }
                },btn2: function(index, layero){
                    vm.killJob(logId, function(){
                        $("#layui-layer"+index).find(".layui-layer-btn").find(".layui-layer-btn1").hide();
                    });
                    return false;
                }
            });
            if(!isRun){
                $("body").find(".layui-layer-btn").find(".layui-layer-btn0").hide();
                $("body").find(".layui-layer-btn").find(".layui-layer-btn1").hide();
            }
        },
        saveOrUpdateJobInfo: function(){
            vm.convertSelectVal();
            $.ajax({
                type: "POST",
                url: baseURL + "dataworks/flow/bindJob?id="+vm.flow.id,
                contentType: "application/json",
                data: JSON.stringify(vm.jobinfo),
                success: function(r){
                    if(r.code == 0){
                        layer.msg("操作成功", {icon: 1});
                        vm.showJobInfoAdd = false;
                        vm.flow.jobinfoId = r.data;
                    }else{
                        layer.alert(r.msg);
                    }
                }
            });
        },
        jobInfoAddBack: function(){
            vm.showJobInfoAdd = false;
        },
        executeLog: function(){
            $.ajax({
                type: "GET",
                url: baseURL + "joblog/lastJob?xxlJobId=" + vm.flow.jobinfoId,
                contentType: "application/json",
                success: function (r) {
                    if (r.code == 0) {
                        if(r.data != null){
                            if(r.data.triggerCode == 200 && r.data.handleCode == 0){
                                vm.showDetail(r.data.id, true);
                            }else{
                                vm.showDetail(r.data.id, false);
                            }
                        }else{
                            layer.msg("暂无执行任务", {icon: 1});
                        }
                    } else {
                        layer.alert(r.msg);
                    }
                }
            });
        },
        bindJob: function(event){
            vm.showJobInfoAdd = true;
            $("#jobInfoForm")[0].reset();
            if(vm.flow.jobinfoId == null){
                vm.title = "新增调度任务";
                $("#scheduleType").val("CRON");
                $("#jobGroup").removeAttr("disabled");
                vm.jobinfo = {triggerStatus: 0, addressType: 0, executorHandler: 'executorJobHandler',scheduleConf: '0 0 1 * * ?'};
            }else{
                $.get(baseURL + "/jobinfo/loadById?id="+vm.flow.jobinfoId, function(r){
                    if(r.code == 200){
                        vm.showJobInfoAdd = true;
                        if(r.content == null){
                            vm.title = "新增调度任务";
                            $("#scheduleType").val("CRON");
                            $("#jobGroup").removeAttr("disabled");
                            vm.jobinfo = {triggerStatus: 0,addressType: 0, executorHandler: 'executorJobHandler',scheduleConf: '0 0 1 * * ?'};
                        }else{
                            vm.title = "编辑调度任务";
                            vm.jobinfo = r.content;
                            vm.convertSelectVal(vm.jobinfo);
                        }
                    }else{
                        alert(r.msg);
                    }
                });
            }
        },
        showSenior: function(obj, domId){
            var senior = obj.innerHTML;
            if(senior == "展开"){
                $("#"+domId).show();
                event.target.innerHTML = "隐藏";
            }else{
                $("#"+domId).hide();
                event.target.innerHTML = "展开";
            }
        }
	}
});